//
//  ComposeView.swift
//  WeiBo
//
//  Created by 陈贵 on 15/9/22.
//  Copyright © 2015年 hzj. All rights reserved.
//

import UIKit

class ComposeView: UIViewController,UITextViewDelegate {
    
    //toolbar的底部约束
    private var toolbarBottomCons: NSLayoutConstraint?
//    theTextView的底部约束
    private var textViewBottomConstraint: NSLayoutConstraint?
    //照片选择器的高度约束
    private var pictureSelectHeight: NSLayoutConstraint?
    
    

    override func viewDidLoad() {
        super.viewDidLoad()
        //通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector:"changeTheToolbar:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
//    UIKeyboardAnimationCurveUserInfoKey = 7;
//    UIKeyboardAnimationDurationUserInfoKey = "0.25";
//    UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
//    UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
//    UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 796}";
//    UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
//    UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
//    UIKeyboardIsLocalUserInfoKey = 1;
    
    @objc private func changeTheToolbar(notification:NSNotification){
        
//        print(notification.userInfo!)
        let h = notification.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
//        print(h.origin.y)
        toolbarBottomCons?.constant = -UIScreen.mainScreen().bounds.height + h.origin.y
        UIView.animateWithDuration(0.25) {
            self.view.layoutIfNeeded()
        }
    }
    
    
    //设置界面
    override func loadView() {
        view = UIView()
        view.backgroundColor = UIColor.brownColor()
        
        
        //禁止缩进
        automaticallyAdjustsScrollViewInsets = false
        
        setNav()
        setToolbar()
        setTextView()
        setPicture()
        
        
//         let search = UISearchBar()
//        view.addSubview(search)
//        search.frame = CGRectMake(100 , 100, 100, 50)
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        theTextView.becomeFirstResponder()
    }
    //导航栏
    private func setNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        let bth = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "compose")
        bth.enabled = false
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "compose")
        
        //添加搜索
//        let search = UISearchBar()
//        search.frame = CGRectMake(10, 10, 100, 50)
//        navigationItem.titleView = search

//        navigationItem.title = "发送微博"
    }
    //关闭
    @objc private func close(){
        theTextView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    //发送
    @objc private func compose(){
        print("发送微博")
    }
    
    //工具栏
    private func setToolbar(){
        view.addSubview(toolBar)
        toolBar.backgroundColor = UIColor.greenColor()
        //约束
        toolBar.translatesAutoresizingMaskIntoConstraints = false
        view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 50))
        
        view.addConstraint(NSLayoutConstraint(item: toolBar, attribute: NSLayoutAttribute.Bottom , relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
        
        toolbarBottomCons = view.constraints.last

        


        /// 添加按钮
        //图标数组
        let nameArray = [["iconName":"compose_toolbar_picture","action":"selectPicture"],["iconName":"compose_toolbar_picture"],["iconName":"compose_toolbar_picture"],["iconName":"compose_toolbar_picture"],["iconName":"compose_toolbar_picture"]]
        //按钮数组
        
        var items = [UIBarButtonItem]()
        for dic in nameArray {
//            //建按钮
//            let bth = UIButton(imageName: dic["iconName"]!)
//            //添事件
//            if let actionName = dic["action"] {
//                bth.addTarget(self, action: Selector(actionName), forControlEvents: UIControlEvents.TouchUpInside)
//            }
//            
//            items.append(UIBarButtonItem(customView: bth))
            
            items.append(UIBarButtonItem(imageName: dic["iconName"]!, target: self, actionName: dic["action"]))
            //加站位空格
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
 
        }
        //移除最后一个站位按钮
        items.removeLast()
        toolBar.items = items
        
    }
    
    
    
    
    
    
    
    @objc private func selectPicture(){
        print("选择图片")
        
        view.removeConstraint(textViewBottomConstraint!)
        
        textViewBottomConstraint = NSLayoutConstraint(item: theTextView, attribute: NSLayoutAttribute.Bottom , relatedBy: NSLayoutRelation.Equal, toItem: pictureSelectVC.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
        view.addConstraint(textViewBottomConstraint!)
        pictureSelectHeight?.constant = UIScreen.mainScreen().bounds.height * 0.6
//        print(UIScreen.mainScreen().bounds.height)
        view.layoutIfNeeded()
        
    }
    
    
    
    
    
    
 /// 文本框
    private func setTextView(){
//        let theTextView = theTextView
        theTextView.backgroundColor = UIColor.whiteColor()
    
        view.addSubview(theTextView)
        
        theTextView.translatesAutoresizingMaskIntoConstraints = false
        //约束
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[TV]-0-|", options: [], metrics: nil, views: ["TV":theTextView]))
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[top]-0-[TV]-0-[tool]", options: [], metrics: nil, views: ["top":topLayoutGuide,"TV":theTextView,"tool":toolBar]))

        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[top]-0-[TV]", options: [], metrics: nil, views: ["top":topLayoutGuide,"TV":theTextView]))
        view.addConstraint(NSLayoutConstraint(item: theTextView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: toolBar, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
        
        textViewBottomConstraint = view.constraints.last
        
        theTextView.addSubview(textLable)

        textLable.translatesAutoresizingMaskIntoConstraints = false
        theTextView.addConstraint(NSLayoutConstraint(item: textLable, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: theTextView, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 5))
        theTextView.addConstraint(NSLayoutConstraint(item: textLable, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: theTextView, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 8))
        theTextView.addConstraint(NSLayoutConstraint(item: textLable, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: textLable.bounds.width))
        theTextView.addConstraint(NSLayoutConstraint(item: textLable, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: textLable.bounds.height))
    }
    
    //textView的代理方法
    func textViewDidChange(textView: UITextView) {
        textLable.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
 /// 照片选择器
    func setPicture(){
        let pv = pictureSelectVC.view
        
        view.insertSubview(pv, belowSubview: toolBar)
        //        view.addSubview(pv)
        //必须将控制器也加入
        addChildViewController(pictureSelectVC)
        
        
        
        let h = UIScreen.mainScreen().bounds.height
        pv.translatesAutoresizingMaskIntoConstraints = false
        
        view.addConstraint(NSLayoutConstraint(item: pv, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: pv, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0))
        view.addConstraint(NSLayoutConstraint(item: pv, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
//        view.addConstraint(NSLayoutConstraint(item: pv, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: h * 0.6))
        view.addConstraint(NSLayoutConstraint(item: pv, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 0))

        
        pictureSelectHeight = view.constraints.last

}
    
    //MARK: - 懒加载
    //工具
    private lazy var toolBar:UIToolbar = UIToolbar()
    //文本
    private lazy var theTextView:UITextView = {
        let tv = UITextView()
        tv.font = UIFont.systemFontOfSize(17)
        //设置代理
        tv.delegate = self
        //可拖动
        tv.alwaysBounceVertical = true
        //键盘消失机制
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        return tv
    }()
    //文本里的标签
    private lazy var textLable:UILabel = UILabel(title: "好心情，一起分享吧....", color: UIColor(white: 0.8, alpha: 1), fontSize: 17)
    //照片选择器
    private lazy var pictureSelectVC:pictureSelectController = pictureSelectController()
  
}
